package com.eastseeway.radioproject.engineer;

import android.os.Environment;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.eastseeway.radioproject.RadioApplication;
import com.eastseeway.radioproject.base.BaseRepository;
import com.eastseeway.radioproject.database.ElectrodeDao;
import com.eastseeway.radioproject.database.RadioProjectDatabase;
import com.eastseeway.radioproject.database.VBusDao;
import com.eastseeway.radioproject.entities.Bean1FromHandle;
import com.eastseeway.radioproject.entities.BeanFromBottomBoard;
import com.eastseeway.radioproject.entities.BeanFromEnergyBoard;
import com.eastseeway.radioproject.entities.BeanFromNegativePressureBoard;
import com.eastseeway.radioproject.entities.BeanFromSwitchBoard;
import com.eastseeway.radioproject.entities.BeanOfElectrode;
import com.eastseeway.radioproject.entities.BeanVBus;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class EngineerRepository extends BaseRepository {

    private final ElectrodeDao mElectrodeDao;
    private final VBusDao mVBusDao;

    public EngineerRepository() {
        super();
        mElectrodeDao = RadioProjectDatabase.getInstance(RadioApplication.getInstance()).getElectrodeDao();
        mVBusDao = RadioProjectDatabase.getInstance(RadioApplication.getInstance()).getVBusDao();
    }

    protected void insertVBusData(BeanVBus beanVBus){
        executorService.submit(()->{
           mVBusDao.insertVBus(beanVBus);
        });
    }


    protected void insertElectrodeData(){
        executorService.submit(() -> {
            try {
                String path = Environment.getExternalStorageDirectory().getPath()+"/RadioProject/electrode.xls";
                FileInputStream fileInputStream = new FileInputStream(path);
                HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
//              XSSFWorkbook用来读取.xlsx文件，但是不知道为什么这个类型的文件读取不了，只能用.xls
//                XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
                Sheet sheet = workbook.getSheetAt(0);
                for (Row row : sheet) {
                    int columns = row.getLastCellNum();
                    BeanOfElectrode beanOfElectrode = new BeanOfElectrode();
                    for (int i = 0; i < columns; i++) {
                        Cell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
                        if (cell != null) {
                            switch (i) {
//                            温度	功率	刺入深度	针头	能量	作用时长
                                case 0:beanOfElectrode.setId(cell.toString());break;
                                case 1:beanOfElectrode.setTargetTemp(cell.toString());break;
                                case 2:beanOfElectrode.setPower(cell.toString());break;
                                case 3:beanOfElectrode.setDepth(cell.toString());break;
                                case 4:beanOfElectrode.setNumber(cell.toString());break;
                                case 5:beanOfElectrode.setEnergy(cell.toString());break;
                                case 6:beanOfElectrode.setDuration(cell.toString());break;
                            }
                        }
                    }
                    mElectrodeDao.addElectrode(beanOfElectrode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    LiveData<List<BeanVBus>> queryVBusByHandleTypeAndFreq(String handleType,String freq){
        return mVBusDao.queryVBusByHandleTypeAndFreq(handleType,freq);
    }

    //    更新负压控制板的数据
    public LiveData<List<EngineerItemBean>> updatePressureBoard(BeanFromNegativePressureBoard bean) {
        MutableLiveData<List<EngineerItemBean>> pressureLiveData = new MutableLiveData<>();
        executorService.submit(() -> {pressureLiveData.postValue(getNegativePressureBoardData(bean));});
        return pressureLiveData;
    }
    //    初始化负压控制板的数据
    public List<EngineerItemBean> getNegativePressureBoardData(BeanFromNegativePressureBoard beanFromNegativePressureBoard) {
        List<EngineerItemBean> negativePressureCachedItems = new ArrayList<>();
        negativePressureCachedItems.add(new EngineerItemBean("储气罐传感器压力值",   String.valueOf(beanFromNegativePressureBoard.getGas_Container_Press())));
        negativePressureCachedItems.add(new EngineerItemBean("储气罐传感器温度值",   String.valueOf(beanFromNegativePressureBoard.getGas_Container_Temp())));
        negativePressureCachedItems.add(new EngineerItemBean("手柄连接传感器管路压力值",String.valueOf(beanFromNegativePressureBoard.getGas_Pipe_Press())));
        negativePressureCachedItems.add(new EngineerItemBean("手柄连接传感器管路温度值",String.valueOf(beanFromNegativePressureBoard.getGas_Pipe_Temp())));
        negativePressureCachedItems.add(new EngineerItemBean("手柄端请求的压力值",   String.valueOf(beanFromNegativePressureBoard.getHandle_Gas_Press())));
        negativePressureCachedItems.add(new EngineerItemBean("电机工作电流",      String.valueOf(beanFromNegativePressureBoard.getMotor_I())));
        negativePressureCachedItems.add(new EngineerItemBean("电机工作温度",      String.valueOf(beanFromNegativePressureBoard.getMotor_T())));
        negativePressureCachedItems.add(new EngineerItemBean("CPU工作温度",     String.valueOf(beanFromNegativePressureBoard.getCPU_T())));
        negativePressureCachedItems.add(new EngineerItemBean("输入电源电压",      String.valueOf(beanFromNegativePressureBoard.getInput_power_V())));
        negativePressureCachedItems.add(new EngineerItemBean("7805转5V输出电压", String.valueOf(beanFromNegativePressureBoard.getSt78m05_V())));
        int faultStatus = beanFromNegativePressureBoard.getFAULT_STATUS();
        negativePressureCachedItems.add(new EngineerItemBean("电机驱动芯片检测到电流异常", String.valueOf(faultStatus & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("电机温度异常",        String.valueOf((faultStatus >> 1) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("负压泵工作超时",       String.valueOf((faultStatus >> 2) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("与手柄连接管路调压时超时",  String.valueOf((faultStatus >> 3) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("气缸压力低，不能充气",    String.valueOf((faultStatus >> 4) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("CPU温度异常",       String.valueOf((faultStatus >> 5) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("输入电源电压偏差大",     String.valueOf((faultStatus >> 6) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("CPU供电偏差大",      String.valueOf((faultStatus >> 7) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("调压失效",          String.valueOf((faultStatus >> 8) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("未接收到手柄端压力设置值",  String.valueOf((faultStatus >> 9) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("接收队列满错误",       String.valueOf((faultStatus >> 10) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("气体容器压力传感器采样超时", String.valueOf((faultStatus >> 11) & 0x01)));
        negativePressureCachedItems.add(new EngineerItemBean("管路压力传感器采样超时",   String.valueOf((faultStatus >> 12) & 0x01)));
        return negativePressureCachedItems;
    }


//    初始化底板的数据
    public List<EngineerItemBean> getBottomBoardData(BeanFromBottomBoard beanFromBottomBoard) {
        List<EngineerItemBean> bottomBoardDataList = new ArrayList<>();
        bottomBoardDataList.add(new EngineerItemBean("底板电源总线电压(V)", String.valueOf(beanFromBottomBoard.getVbus_v())));
        bottomBoardDataList.add(new EngineerItemBean("底板电源总线电流(mA)", String.valueOf(beanFromBottomBoard.getIbus_mA())));
        bottomBoardDataList.add(new EngineerItemBean("机箱工作温度", String.valueOf(beanFromBottomBoard.getBox_T())));
        bottomBoardDataList.add(new EngineerItemBean("AM1117转3.3V输出电压", String.valueOf(beanFromBottomBoard.getAM11173v3_V())));
        bottomBoardDataList.add(new EngineerItemBean("接收到的Vbus设置值V", String.valueOf(beanFromBottomBoard.getVbus_Set_Value())));
        bottomBoardDataList.add(new EngineerItemBean("fault", Integer.toHexString(beanFromBottomBoard.getFault())));

        String devStatus = Integer.toBinaryString(beanFromBottomBoard.getDev_status());
        for (int i = 0; i < devStatus.toCharArray().length; i++) {
            int bitMask = 1 << i;
            int bitValue = (beanFromBottomBoard.getDev_status() & bitMask) == 0 ? 0 : 1;
            switch (i) {
                case 0: bottomBoardDataList.add(new EngineerItemBean("主电源输入反馈", String.valueOf(bitValue))); break;
                case 1: bottomBoardDataList.add(new EngineerItemBean("脚踏开关输入", String.valueOf(bitValue))); break;
                case 2: bottomBoardDataList.add(new EngineerItemBean("主电源开关状态", String.valueOf(bitValue))); break;
                case 3: bottomBoardDataList.add(new EngineerItemBean("显示电源开关状态", String.valueOf(bitValue))); break;
                case 4: bottomBoardDataList.add(new EngineerItemBean("手柄电源开关状态", String.valueOf(bitValue))); break;
                case 5: bottomBoardDataList.add(new EngineerItemBean("负压板电源开关状态", String.valueOf(bitValue)));
                case 6: bottomBoardDataList.add(new EngineerItemBean("风扇电源开关状态", String.valueOf(bitValue))); break;
                case 7: bottomBoardDataList.add(new EngineerItemBean("蜂鸣器电源开关状态", String.valueOf(bitValue))); break;
                case 8: bottomBoardDataList.add(new EngineerItemBean("数控电源开关状态", String.valueOf(bitValue))); break;
            }
        }
        return bottomBoardDataList;
    }
//    更新底板数据
    public LiveData<List<EngineerItemBean>> updateBottomBoard(BeanFromBottomBoard beanFromBottomBoard) {
        MutableLiveData<List<EngineerItemBean>> bottomBoardData = new MutableLiveData<>();
        executorService.submit(() -> {bottomBoardData.postValue(getBottomBoardData(beanFromBottomBoard));});
        return bottomBoardData;
    }


//    获取手柄数据
    public List<EngineerItemBean> getHandleBoardData(Bean1FromHandle bean1FromHandle) {
        ArrayList<EngineerItemBean> handleDataList = new ArrayList<>();
        handleDataList.add(new EngineerItemBean("频率", String.valueOf(bean1FromHandle.getFreq())));
        handleDataList.add(new EngineerItemBean("功率", String.valueOf(bean1FromHandle.getPower())));
        handleDataList.add(new EngineerItemBean("负压值", String.valueOf(bean1FromHandle.getPressure())));
        handleDataList.add(new EngineerItemBean("出针长度", String.valueOf(bean1FromHandle.getDepth())));
        handleDataList.add(new EngineerItemBean("断续脉冲", String.valueOf(bean1FromHandle.getIntermittentDischargePulse())));
        handleDataList.add(new EngineerItemBean("断续高", String.valueOf(bean1FromHandle.getIntermittentDischargeHighLevelPeriod())));
        handleDataList.add(new EngineerItemBean("断续低", String.valueOf(bean1FromHandle.getIntermittentDischargeLowLevelPeriod())));
        handleDataList.add(new EngineerItemBean("连续时间", String.valueOf(bean1FromHandle.getContinuousDischargePeriod())));

        handleDataList.add(new EngineerItemBean("自动出针", String.valueOf(bean1FromHandle.getInterval())));
        handleDataList.add(new EngineerItemBean("剩余次数", String.valueOf(bean1FromHandle.getShengyucishu())));
        handleDataList.add(new EngineerItemBean("皮肤阻抗", String.valueOf(bean1FromHandle.getSkinResistance())));
        handleDataList.add(new EngineerItemBean("mJ功率", String.valueOf(bean1FromHandle.getTotalPower())));
        handleDataList.add(new EngineerItemBean("接触电阻", String.valueOf(bean1FromHandle.getTouchResistance())));
        handleDataList.add(new EngineerItemBean("丝杆位置", String.valueOf(bean1FromHandle.getLeadScrewPosition())));
        handleDataList.add(new EngineerItemBean("版本信息",String.valueOf(bean1FromHandle.getVersion())));

        for (int i = 0; i < 8; i++) {
            int mask = 1 << i;
            int bitValue = (bean1FromHandle.getWorkState() & mask) == 0 ? 0 : 1;
            switch (i) {
                case 0: handleDataList.add(new EngineerItemBean("运行状态", String.valueOf(bitValue)));break;
                case 1: handleDataList.add(new EngineerItemBean("工作模式", String.valueOf(bitValue)));break;
                case 2: handleDataList.add(new EngineerItemBean("自动出针", String.valueOf(bitValue)));break;
                case 3: handleDataList.add(new EngineerItemBean("分层治疗", String.valueOf(bitValue)));break;
                case 4: handleDataList.add(new EngineerItemBean("针头识别", String.valueOf(bitValue)));break;
                case 5: handleDataList.add(new EngineerItemBean("皮肤接触", String.valueOf(bitValue)));break;
                case 6: handleDataList.add(new EngineerItemBean("负压吸附", String.valueOf(bitValue)));break;
                case 7: handleDataList.add(new EngineerItemBean("气压调试", String.valueOf(bitValue)));break;
            }
        }
        for (int i = 0; i < 8; i++) {
            int bitMask = 1 << i;
            int bitValue = (bean1FromHandle.getException() & bitMask) == 0 ? 0 : 1;
            switch (i){
                case 0: handleDataList.add(new EngineerItemBean("计数结束", String.valueOf(bitValue)));break;
                case 1: handleDataList.add(new EngineerItemBean("功率超限", String.valueOf(bitValue)));break;
                case 2: handleDataList.add(new EngineerItemBean("负压值低", String.valueOf(bitValue)));break;
                case 6: handleDataList.add(new EngineerItemBean("丝杆故障", String.valueOf(bitValue)));break;
                case 7: handleDataList.add(new EngineerItemBean("电机卡滞", String.valueOf(bitValue)));break;
            }
        }
        return handleDataList;
    }

//    更新手柄数据
    public LiveData<List<EngineerItemBean>> updateHandleBoard(Bean1FromHandle bean) {
        MutableLiveData<List<EngineerItemBean>> handleData = new MutableLiveData<>();
        executorService.submit(() -> {handleData.postValue(getHandleBoardData(bean));});
        return handleData;
    }

//    获取切换板数据
    public List<EngineerItemBean> getSwitchData(BeanFromSwitchBoard beanFromSwitchBoard){
        ArrayList<EngineerItemBean> switchDataList = new ArrayList<>();
        switchDataList.add(new EngineerItemBean("能量输出时间",String.valueOf(beanFromSwitchBoard.getEnergy_Output_Time())));
        switchDataList.add(new EngineerItemBean("温度",String.valueOf(beanFromSwitchBoard.getBoard_LM75_T())));
        switchDataList.add(new EngineerItemBean("故障信息",String.valueOf(beanFromSwitchBoard.getFault_status())));
        switchDataList.add(new EngineerItemBean("工作状态",String.valueOf(beanFromSwitchBoard.getWk_status())));
        switchDataList.add(new EngineerItemBean("设备状态",String.valueOf(beanFromSwitchBoard.getDev_status())));
        return switchDataList;
    }
    public LiveData<List<EngineerItemBean>> updateSwitchBoard(BeanFromSwitchBoard beanFromSwitchBoard){
        MutableLiveData<List<EngineerItemBean>> switchData = new MutableLiveData<>();
        executorService.submit(()->switchData.postValue(getSwitchData(beanFromSwitchBoard)));
        return switchData;
    }

//    获取能量版数据
    public List<EngineerItemBean> getEnergyBoardData(BeanFromEnergyBoard beanFromEnergyBoard){
        ArrayList<EngineerItemBean> energyDataList = new ArrayList<>();
        energyDataList.add(new EngineerItemBean("版本信息1",String.valueOf(beanFromEnergyBoard.getVersion())));
        energyDataList.add(new EngineerItemBean("版本信息2",String.valueOf(beanFromEnergyBoard.getVersion1())));
        energyDataList.add(new EngineerItemBean("自检",String.valueOf(beanFromEnergyBoard.getSelftestok())));
        energyDataList.add(new EngineerItemBean("温度A",String.valueOf(beanFromEnergyBoard.getTemperature_A())));
        energyDataList.add(new EngineerItemBean("温度B",String.valueOf(beanFromEnergyBoard.getTemperature_B())));
        energyDataList.add(new EngineerItemBean("温度C",String.valueOf(beanFromEnergyBoard.getTemperature_C())));
        energyDataList.add(new EngineerItemBean("上传数据包数",String.valueOf(beanFromEnergyBoard.getNumofpackage())));
        energyDataList.add(new EngineerItemBean("上传数据序号",String.valueOf(beanFromEnergyBoard.getSequenceofpackage())));
        energyDataList.add(new EngineerItemBean("应答响应",String.valueOf(beanFromEnergyBoard.getNack())));
        energyDataList.add(new EngineerItemBean("接收状态",String.valueOf(beanFromEnergyBoard.isReceiveOk())));
        energyDataList.add(new EngineerItemBean("过压",String.valueOf(beanFromEnergyBoard.isOverVoltage())));
        energyDataList.add(new EngineerItemBean("过流",String.valueOf(beanFromEnergyBoard.isOverCurrent())));
        return energyDataList;
    }

    public LiveData<List<EngineerItemBean>> updateEnergyBoard(BeanFromEnergyBoard beanFromEnergyBoard){
        MutableLiveData<List<EngineerItemBean>> energyData = new MutableLiveData<>();
        executorService.submit(()->energyData.postValue(getEnergyBoardData(beanFromEnergyBoard)));
        return energyData;
    }
    
}
